package com.sujeet.learning.xmlrpc;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class Scheduler {

	private static List<String> events = new ArrayList<String>();

	private static Map<String, Date> eventDetails = new HashMap<String, Date>();

	private static boolean eventsSorted;

	public Scheduler() {
		eventsSorted = true;
	}

	public boolean addEvent(String eventName, Date eventTime) {
		// Add this event to the list of events
		if (!events.contains(eventName)) {
			events.add(eventName);
			eventDetails.put(eventName, eventTime);
			eventsSorted = false;
			Thread sorterThread = new Thread(new Runnable() {
					@Override
					public void run() {
						sortEvents();						
					}
			});
			sorterThread.start();
		}
		return true;
	}

	public synchronized boolean removeEvent(String eventName) {
		events.remove(eventName);
		eventDetails.remove(eventName);
		return true;
	}

	public List getListOfEvents() {
		List<String> list = new ArrayList<String>();
		// Create a Date Formatter
		SimpleDateFormat fmt = new SimpleDateFormat("hh:mm a MM/dd/yyyy");
		// Add each event to the list
		for (int i = 0; i < events.size(); i++) {
			String eventName = (String) events.get(i);
			list.add("Event \"" + eventName + "\" scheduled for "
					+ fmt.format((Date) eventDetails.get(eventName)));
		}

		return list;
	}

	private synchronized void sortEvents() {
		if (eventsSorted) {
			return;
		}
		// Create array of events as they are (unsorted)
		String[] eventNames = new String[events.size()];
		eventNames = events.toArray(eventNames);
		// Bubble sort these
		String tmpName;
		Date date1, date2;
		for (int i = 0; i < eventNames.length - 1; i++) {
			for (int j = 0; j < eventNames.length - i - 1; j++) {
				// Compare the dates for these events
				date1 = (Date) eventDetails.get(eventNames[j]);
				date2 = (Date) eventDetails.get(eventNames[j + 1]);
				if (date1.compareTo(date2) > 0) {
					// Swap if needed
					tmpName = eventNames[j];
					eventNames[j] = eventNames[j + 1];
					eventNames[j + 1] = tmpName;
				}
			}
		}
		// Put into new Vector (ordered)
		List<String> sortedEvents = new ArrayList<String>();
		for (int i = 0; i < eventNames.length; i++) {
			sortedEvents.add(eventNames[i]);
		}
		// Update the global events
		events = sortedEvents;
		eventsSorted = true;
	}

}
